package com.lion.common.modules.uaa.common.assistants;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JwtAssist {
    public static final String USERCODE = "userCode";
    public static final String USERNAME = "username";
    public static final String AUTHORITIES = "authorities";
    public static final String BEARER = "Bearer ";

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.access-token-expiration}")
    private Long accessTokenExpiration;

    @Value("${jwt.refresh-token-expiration}")
    private Long refreshTokenExpiration;

    private SecretKey getSecretKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }

    /**
     * 生成访问令牌
     */
    public String generateAccessToken(Long userCode, String username, List<String> authorities) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(USERCODE, userCode);
        claims.put(USERNAME, username);
        claims.put(AUTHORITIES, authorities);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + accessTokenExpiration * 1000))
                .signWith(getSecretKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 生成刷新令牌
     */
    public String generateRefreshToken(Long userCode, String username) {
        return Jwts.builder()
                .setSubject(username)
                .claim(USERCODE, userCode)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + refreshTokenExpiration * 1000))
                .signWith(getSecretKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 验证令牌是否有效
     */
    public boolean validateToken(String token) {
        // 判断是否为空
        if (token == null) {
            return false;
        }
        // 分析前缀
        if (token.startsWith(BEARER)) {
            token = token.substring(BEARER.length());
        }

        // 解析令牌
        try {
            Jwts.parserBuilder().setSigningKey(getSecretKey()).build().parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 从令牌中获取用户编码
     */
    public Long getUserCodeFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(getSecretKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims.get(USERCODE, Long.class);
    }

    // === 新增的两个关键方法 ===
    public Long getAccessTokenExpiration() {
        return accessTokenExpiration;
    }

    public Long getRefreshTokenExpiration() {
        return refreshTokenExpiration;
    }

    // === 令牌解析 ===
    public Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSecretKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    // === 获取令牌信息 ===
    public List<String> getAuthoritiesFromToken(String token) {
        return parseToken(token).get(AUTHORITIES, List.class);
    }

    // === 剩余时间计算 ===
    public Long getRemainTime(String token) {
        Claims claims = parseToken(token);
        return (claims.getExpiration().getTime() - System.currentTimeMillis()) / 1000;
    }

    ///////////////////////////////////////////////

    public String getUserIdFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(secret.getBytes())
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }

    public List<String> getRolesFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(secret.getBytes())
                .build()
                .parseClaimsJws(token)
                .getBody();
        return claims.get(AUTHORITIES, List.class);
    }
}